package com.bestcem.xm.common.core.uitls;

/**
 * @author ming.xue <ming.xue@idiaoyan.com>
 * @desc 解码器
 * @date 2021-09-23
 */
public class DecoderUtil<K, V> {
    private K condition;
    private V defaults;
    private V value;
    private boolean matched;

    public DecoderUtil(K condition) {
        this.condition = condition;
        this.matched = false;
    }

    public DecoderUtil(K condition, V defaults) {
        this.condition = condition;
        this.defaults = defaults;
        this.matched = false;
    }

    public static <K, V> DecoderUtil<K, V> create(K condition) {
        return new DecoderUtil<>(condition);
    }

    public static <K, V> DecoderUtil<K, V> create(K condition, V defaults) {
        return new DecoderUtil<>(condition, defaults);
    }

    public DecoderUtil<K, V> decode(K key, V value) {
        if (this.matched) return this;

        if (this.equal(this.condition, key)) {
            this.matched = true;
            this.value = value;
        }

        return this;
    }

    public DecoderUtil<K, V> defaults(V value) {
        this.defaults = value;
        return this;
    }

    public V get() {
        if (this.matched) return this.value;

        return this.defaults;
    }

    private <T> boolean equal(T obj1, T obj2) {
        if (obj1 == null || obj2 == null)
            return obj1 == obj2;
        return obj1.equals(obj2);
    }
}